/**
	日志
 */
package dao

import (
	"fmt"
	"time"
)

type log struct {
	Lid int `json:"lid" gorm:"column:lid"`
	Uid int `json:"uid" gorm:"column:uid"`
	Type string `json:"type" gorm:"column:type"`
	Content string `json:"content" gorm:"column:content"`
	Ip string `json:"ip" gorm:"column:ip"`
	Headers string `json:"headers" gorm:"column:headers"`
	Ctime int64 `json:"c_time" gorm:"column:c_time"`
}
/**
	日志入库
 */
func (l *log) Add (uid int, username string,content string,ip string,headers string, logType string) bool {

	//{xxx}于{2006-01-02 15:04:05}{操作}{内容}
	now := time.Now()
	//now_format := now.Format("2006-01-02 15:04:05")

	con := "%s:{%s}"
	//con = fmt.Sprintf(con,username,now_format,content)
	con = fmt.Sprintf(con,username,content)
	var lg log
	lg.Content = con
	lg.Ip = ip
	lg.Uid = uid
	lg.Headers = headers
	lg.Type = logType
	lg.Ctime = now.Unix()

	b := true
	err := db.Create(&lg).Error
	if err != nil{
		b = false
		panic(err)
	}
	return b

}
func (l *log) List(pageIndex int,pageSize int, startTime int, stopTime int) ([]log, int, error) {
	var log []log

	table := db.Table("bc_log").Select("*")
	if l.Content != "" {
		table = table.Where("content like ?", "%" + l.Content + "%" )
	}
	if startTime != 0 {
		table = table.Where("c_time >= ?", startTime)
	}
	if stopTime != 0 {
		table = table.Where("c_time <= ?", stopTime)
	}
	var count int

	if err := table.Select("lid,type,content,ip,headers,c_time").
		Order("lid desc").
		Offset((pageIndex - 1) * pageSize).Limit(pageSize).Find(&log).Error; err != nil {
		return nil, 0, err
	}
	table.Table("bc_log").Count(&count)
	return log, count, nil
}
var LogDao = &log{}
